// counter that is incremented each time a new task is added to the page
// this is used in order to count current tasks + newly added, so i can retrieve older tasks
// that are older than current + newly added
var new_tasks_added = 0;
var old_pages_loaded = 0;
var lang = 'bg'; // default language


var session_timer = 0;
var session_expire = 7200; // default value - 2 hours
// should be called after each ajax request to the server (because the session is reset at this moment)
function resetSessionTimer(){
	session_timer = 0;
}

function incrementSessionTimer(){
	session_timer += 10;
	//console.log(session_timer);
	//console.log(session_expire);
	if(session_timer > (session_expire+10)){
		// session has expired;
		// 120 (sec) is for tolerance in case timer counting in js has deviations from timer counting in the server
		resetSessionTimer();
		location.href = localizeUrl('/');
	}
	setTimeout( incrementSessionTimer, 10000); // increment timer and check session timeout each 10 seconds
}


$(document).ready(function(){

	// get lang sent from server
	lang = $('#lang').html();

	// load some server variables passed from the server
	// js_cfg.sess_expire will be used to make a timer and detect if the session has expired
	var js_cfg = jQuery.parseJSON( $('#js_cfg').val() );
	session_expire = parseInt(js_cfg.session_expire, 10) > 0 ? parseInt(js_cfg.session_expire, 10) : 7200;
	resetSessionTimer();
	incrementSessionTimer();
	

	// initialize date picker format
	$('#duedate').datepicker({
		firstDay : 1,
		dateFormat : 'dd-mm-yy'
	});

	/*
	// can be used like $('#edit_textarea').is(':focused') == true
	jQuery.extend(jQuery.expr[':'], {
		focused: function(element) { 
			return element == document.activeElement; 
		}
	});
	*/

	$(document).bind('keydown', function(e){
		
		// handle ESC key to close edit dialog
		if(e.keyCode === 27) { 
			if($('#task_edit').is(':visible')){
				closeEditDialog(); 
			}
		}
		
		// handle ENTER key to save task
		if(e.keyCode == 13 && !e.ctrlKey && !e.shiftKey) {
			if($('#task_edit').is(':visible')){
				e.preventDefault();
				$('#btn_savetask').focus();
				$('#btn_savetask').click();
			}
		}
		// handle ENTER key in textarea to dispatch ENTER keypress when ENTER+CTRL is pressed (works in Gecko browsers)
		else if(e.keyCode == 13 && e.ctrlKey){
			var evt = document.createEvent("KeyboardEvent");
			evt.initKeyEvent(
							"keypress", 
							true, 
							true, 
							null,
							false,
							false,
							false,
							false,
							13,
							0);
			
			document.getElementById('edit_textarea').dispatchEvent(evt);
		}
	});


	$('#btn_addtask').click(function(e){
		e.preventDefault();
		$('#btn_addtask').attr('disabled', true);
		var content = jQuery.trim( $('#taskcontent').val() );
		var current_tag_id = parseInt($('#current_tag_id').html(), 10);
		if(content === "")
		{
			$('#btn_addtask').attr('disabled', false);
			alert(L10N['empty_task']);
		}
		else
		{	
			$.ajax({
				url	: localizeUrl('/tasks/add'),
				type : 'post',
				dataType: 'json',
				data : ({ action:'addtask', taskcontent : content, tag_id : current_tag_id }),
				timeout : 15000,
				success : function(msg){
					if(msg.status === "OK")
					{
						$('#today tbody').prepend(msg.task);
						$('#taskcontent').val('').focus();
						new_tasks_added++;
					}
					else
					{
						alert(L10N['add_task_err']);
					}
				},
				complete : function(){
					$('#btn_addtask').attr('disabled', false);
					resetSessionTimer();
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					// if session has expired, an error shall be returned so redirect to login
					location.href = localizeUrl('/'); // redirect to home page (login)
				}
			});	
		}
	});
	
	
	$('.minus').live('click', function(e){
		e.preventDefault();
		var tableid = $(e.currentTarget).parents('table').attr('id');
		$('#'+tableid+' tbody').hide();
		$(e.currentTarget).removeClass('minus');
		$(e.currentTarget).addClass('plus');
		$(e.currentTarget).blur();
	});

	
	$('.plus').live('click', function(e){
		e.preventDefault();		
		var tableid = $(e.currentTarget).parents('table').attr('id');
		$('#'+tableid+' tbody').show();
		$(e.currentTarget).removeClass('plus');
		$(e.currentTarget).addClass('minus');
		$(e.currentTarget).blur();
	});


	$('.task_checkbox').live('click', function(e){
		var state;
		var id = e.currentTarget.id;
		if( $(e.currentTarget).is(':checked') )
		{
			state = 1;
			$('#contentid_'+id).addClass('stroke');
		}
		else
		{
			state = 0;
			$('#contentid_'+id).removeClass('stroke');
		}

		$.ajax({
			url	: localizeUrl('/tasks/state'),
			type : 'post',
			data : ({ task_id : id, state : state }),
			dataType : 'text',
			timeout : 15000,
			success : function(msg){
				resetSessionTimer();
				if(msg !== 'ok')
					alert(L10N['error']);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				// if session has expired, an error shall be returned so redirect to login
				location.href = localizeUrl('/'); // redirect to home page (login)
			}
		});
	});
	
	
	// handle click on the task content. 
	// display mask div for background-color and task edit dialog on top
	$('.task_content').live('click', function(e){			
		// OPERA HACK - put the textarea inside the edit dialog (td) each time the dialog is opened and remove it
		// each time it is closed, because otherwise the value of the task area cannot be retrieved on
		// btn_savetask CLICK
		$('#td_textarea').html('<textarea id="edit_textarea" class="edit_textarea" rows="5"></textarea>');
		//$("#edit_textarea").keydown(function(){ $("#edit_textarea").css('display','block'); });
		
		var spanid = e.currentTarget.id;
		var tmp = spanid.split('_');
		var taskid = tmp[1] | 0;
		$('#h_task_id').val(taskid);
	
		// set dialog input boxes
		var content = jQuery.trim( $('#contentid_'+taskid).html() );
		$('#edit_textarea').val( html_entity_decode(content) );
		$('#edit_tags').val( html_entity_decode($('#tags_'+taskid).val()) );
		
		var duedate = $('#duedate_'+taskid).val();
		//alert( new Date(duedate).toGMTString() );
		$('#duedate').val( duedate );

		// display the mask
		var maskHeight = $(document).height();     
		var maskWidth = $(document).width();
		$('#task_edit_bgmask').css({'width':maskWidth,'height':maskHeight});
		$('#task_edit_bgmask').show();
		
		// display the dialog
		var x = ( $(window).width() - $('#task_edit').width() ) / 2;
		var y = $(document).scrollTop() + 120;
		
		$('#task_edit').css('left', x);
		$('#task_edit').css('top', y);
		$('#task_edit').show();
		
		$('#edit_textarea').focus();
	});
	
	
	//$("#edit_textarea").keydown(function(){ $("#edit_textarea").css('display','block'); });
	//$("#edit_textarea").live('keydown', function(){ $("#edit_textarea").css('display','block'); });
	
	$('#btn_savetask').live('click', function(e){
		e.preventDefault();
		$('#ajaxloader').show();
		$('#btn_savetask').attr('disabled', true);
		$('#btn_cancel').attr('disabled', true);
		
		//var content = jQuery.trim( $('#edit_textarea').val() );
		//var content = document.getElementById("edit_textarea").value;
		//alert(content);

		var task_id = $('#h_task_id').val();
		var content = jQuery.trim( $('#edit_textarea').val() );
		//var content = document.getElementById("edit_textarea").value;
		//alert(content);
		
		// old tags are used later to compare in backend php with tags to see if the tags have been modified
		var old_tags = $('#tags_'+task_id).val(); // the tags inserted in the beginning of page load
		var tags = $('#edit_tags').val(); // these are possibly modified tags
		var duedate = $('#duedate').val();
		if(content === "")
		{
			alert(L10N['empty_task']);
			$('#btn_savetask').attr('disabled', false);
			$('#btn_cancel').attr('disabled', false);
			$('#ajaxloader').hide();
		}
		else
		{	
			//console.log(task_id);
			//console.log(content);
			//console.log(tags);
			//console.log(duedate);
			
			$.ajax({
				url	: localizeUrl('/tasks/save'),
				type : 'post',
				dataType: 'json',
				timeout : 15000,
				data : ({ 
							action:'savetask', 
							task_id:task_id, 
							taskcontent : content, 
							tasktags : tags, 
							oldtags : old_tags, 
							duedate : duedate
						}),
				success : function(msg){
					if(msg.status === 'OK')
					{
						//$('#contentid_'+task_id).html( $(content).text(value).html() );
						//console.log(msg);
						//console.log('#contentid_'+task_id);
						
						$('#contentid_'+task_id).html( msg.content );
						$('#tags_'+task_id).val(msg.tags);
						$('#duedate_'+task_id).val( duedate );
						$('#contentid_'+task_id).attr('title', msg.tags);
					}
					else
					{
						alert(L10N['save_task_err']);
					}
				},
				complete : function() {
					$('#ajaxloader').hide();
					$('#btn_savetask').attr('disabled', false);
					$('#btn_cancel').attr('disabled', false);
					closeEditDialog();
					resetSessionTimer();
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					// if session has expired, an error shall be returned so redirect to login
					location.href = localizeUrl('/'); // redirect to home page (login)
				}
			});	
		}		

	});

	
	$('#btn_cancel').live('click', function(e){
		closeEditDialog();
	});
	
	
	$('#close_dialog_link').live('click', function(e){
		e.preventDefault();
		closeEditDialog();
	});
	
	
	function closeEditDialog() {
		if( $( '#task_edit' ).css('display') !== 'none' )
		{
			$('#task_edit').hide();
			$('#task_edit_bgmask').hide();
			$('#edit_textarea').val('');
			$('#edit_tags').val('');
			$('#duedate').val('');
			$('#td_textarea').html('');		
		}
	}
	
	
	// delete task
	$('.down_link').live('click', function(e){
		e.preventDefault();
		var linkid = e.currentTarget.id;
		var tmp = linkid.split('_');
		var task_id = tmp[1] | 0;
		
		if( $('#submenu_'+task_id).is(':visible') ){
			$('#submenu_'+task_id).hide();
		}
		else {
			$('#submenu_'+task_id).show();
		}
		$(this).blur();
	});
	
	
	$('.task_submenu').live('mouseleave', function(){
		$(this).hide();
	});
	
	
	$('.task_delete_link').live('click', function(e){
		e.preventDefault();

		// get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(document).width();
		$('#task_edit_bgmask').css({'width':maskWidth,'height':maskHeight});
		$('#task_edit_bgmask').show();

		$('#ajaxloader-big').css('left', $(window).width()/2 - $('#ajaxloader-big').width()/2);
		$('#ajaxloader-big').css('top', $(document).scrollTop() + 200);
		$('#ajaxloader-big').show();

		var linkid = e.currentTarget.id;
		var tmp = linkid.split('_');
		var task_id = tmp[1] | 0;
		
		$.ajax({
			url : localizeUrl('/tasks/delete'),
			type : 'post',
			data : ({ task_id : task_id }),
			dataType : 'text',
			timeout : 15000,
			success : function(msg){
				if(msg == 'ok'){
					$('#tr_'+task_id).remove();
				}
				else{
					alert(L10N['del_task_err']);
				}
			},
			complete : function(){
				$('#ajaxloader-big').hide();
				$('#task_edit_bgmask').hide();
				resetSessionTimer();
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				// if session has expired, an error shall be returned so redirect to login
				location.href = localizeUrl('/'); // redirect to home page (login)
			}
		});
	});
	
	
	$('.priority_link').live('click', function(e){
		e.preventDefault();
		var linkid = e.currentTarget.id;
		var tmp = linkid.split('_');
		var priority = tmp[1];
		var task_id = tmp[2];
		$.ajax({
			url  	 : localizeUrl('/tasks/priority'),
			type 	 : 'post',
			dataType : 'text',
			data	 : ({ task_id:task_id, priority:priority }),
			timeout  : 15000,
			success  : function(msg){
				resetSessionTimer();
				if(msg !== 'ok')
					alert(L10N['error']);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				// if session has expired, an error shall be returned so redirect to login
				//console.log(XMLHttpRequest);
				//console.log(textStatus);
				//console.log(errorThrown);
				location.href = localizeUrl('/'); // redirect to home page (login)
			}
		});
		$('#contentid_'+task_id)[0].className = $('#contentid_'+task_id)[0].className.replace(/\btaskpriority.*?\b/g, '');
		//$('#contentid_'+task_id).removeClass(); // remove all element classes
		$('#contentid_'+task_id).addClass('taskpriority_'+priority);
		$('#submenu_'+task_id).hide();
	});


	// ---------- tags autocomplete ----------- //

	var availableTags = jQuery.parseJSON( html_entity_decode( $( '#str_tags' ).html() ) );
	
	function split( val ) {
		return val.split( /,\s*/ );
	}
	
	function extractLast( term ) {
		return split( term ).pop();
	}

	$( "#edit_tags" )
		// don't navigate away from the field on tab when selecting an item
		.bind( "keydown", function( event ) {
			if ( event.keyCode === $.ui.keyCode.TAB &&
					$( this ).data( "autocomplete" ).menu.active ) {
				event.preventDefault();
			}
		})
		.autocomplete({
			minLength: 2,
			source: function( request, response ) {
				// delegate back to autocomplete, but extract the last term
				response( $.ui.autocomplete.filter(
					availableTags, extractLast( request.term ) ) );
			},
			focus: function() {
				// prevent value inserted on focus
				return false;
			},
			select: function( event, ui ) {
				var terms = split( html_entity_decode(this.value) );
				// remove the current input
				terms.pop();
				// add the selected item
				terms.push( ui.item.value );
				// add placeholder to get the comma-and-space at the end
				terms.push( "" );
				this.value = terms.join( "," );
				return false;
			}
		});	

	// ------------- end of tags autocomplete ----------- //


	$('#older_tasks_link').live('click', function(e){
		e.preventDefault();
		$('#ajax-loader-tasks').show();
		
		var current_tag_id = parseInt($('#current_tag_id').html(), 10);
		var tsTimeStamp = new Date().getTime();

		$.ajax({
			url	 : localizeUrl('/tasks/getOlderTasks'),
			type : 'post',
			dataType : 'json',
			data : ({ new_tasks_added : new_tasks_added, old_pages_loaded : old_pages_loaded, current_tag_id : current_tag_id, time: tsTimeStamp }),
			timeout : 15000,
			success : function(msg) {
				if(msg.status === 'OK') {
					if(msg.html !== '')
					{
						$('#div_tasklist table:last tbody').append(msg.html);
						old_pages_loaded++; // global variable			
					}
					else
					{
						$('#no_more_old_tasks').html(msg.message);
					}
				}
			},
			complete : function(){
				resetSessionTimer();
				$('#ajax-loader-tasks').hide();
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				// if session has expired, an error shall be returned so redirect to login
				location.href = localizeUrl('/'); // redirect to home page (login)
			}
		});
	});

	clock();
});


function clock() {
	var now = new Date();
	
	var hours = now.getHours() + "";
	if(hours.length == 1){
		hours = "0" + hours;
	}
	
	var minutes = now.getMinutes() + "";
	if(minutes.length == 1){
		minutes = "0" + minutes;
	}
	
	var seconds = now.getSeconds() + "";
	if(seconds.length == 1){
		seconds = "0" + seconds;
	}
	
	var outStr = hours+':'+minutes+':'+seconds;
	document.getElementById('clockDiv').innerHTML=outStr;
	setTimeout( clock ,1000 );
}


function showTooltip(e, message, width){
	var x = e.pageX+20;
	var y = e.pageY-20;
	
	if(width*1 > 0) $('#tooltip').css('width', width);	
	$('#tooltip').html(message);
	$('#tooltip').css('left', x);
	$('#tooltip').css('top', y);
	$('#tooltip').show();
}


function hideTooltip(){
	$('#tooltip').hide();	
}


function html_entity_decode(str) {
	var ta=document.createElement("textarea");
	ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
	return ta.value;
}


function localizeUrl(myurl){
	return "/" + lang + myurl;
}
